<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElForm, ElFormItem, ElSelect, ElInput, ElOption, ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getFieldEnumApi } from '@/api/logisticsCompany'

interface SelectOption {
  value: number
  label: string
}

const emit = defineEmits(['submit'])

// 表单数据
const formData = ref({
  company_type: undefined as number | undefined,
  fl_id: undefined as number | undefined,
  name: '',
  status: 1
})

// 表单ref
const formRef = ref<FormInstance>()

// 枚举数据
const enumData = ref({
  parentCompanies: [] as SelectOption[],
  companyTypes: [] as SelectOption[],
  statusOptions: [] as SelectOption[]
})

// 获取枚举数据
const fetchEnumData = async () => {
  try {
    const res = await getFieldEnumApi({ field: 'all' })
    if (res.data) {
      // 转换公司类型选项
      enumData.value.companyTypes = Object.entries(res.data.company_type).map(([value, label]) => ({
        value: parseInt(value),
        label: label as string
      }))

      // 转换状态选项
      enumData.value.statusOptions = Object.entries(res.data.status).map(([value, label]) => ({
        value: parseInt(value),
        label: label as string
      }))

      // 设置上级物流公司列表
      enumData.value.parentCompanies = res.data.parent_companies.map((company) => ({
        value: company.id,
        label: company.name
      }))
    }
  } catch (error) {
    console.error('Failed to fetch enum data:', error)
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    return formData.value
  } catch (error) {
    console.error('Validation failed:', error)
    throw error
  }
}

// 设置表单数据
const setFormData = (data: any) => {
  formData.value = {
    company_type: data.company_type,
    fl_id: data.fl_id,
    name: data.name,
    status: data.status
  }
}

// 表单验证规则
const rules = {
  company_type: [{ required: true, message: '请选择公司类型', trigger: 'change' }],
  fl_id: [{ required: true, message: '请选择上级物流公司', trigger: 'change' }],
  name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 监听公司类型变化
watch(
  () => formData.value.company_type,
  (newType) => {
    if (newType === 1) {
      formData.value.fl_id = undefined
    }
    if (!newType) {
      formData.value.name = ''
      formData.value.fl_id = undefined
    }
  }
)

// 页面加载时获取枚举数据
onMounted(() => {
  fetchEnumData()
})

// 暴露方法给父组件
defineExpose({
  submitForm,
  setFormData
})
</script>

<template>
  <ElForm ref="formRef" :model="formData" :rules="rules" label-width="120px">
    <!-- 公司类型 -->
    <ElFormItem label="公司类型" prop="company_type">
      <ElSelect v-model="formData.company_type" placeholder="请选择公司类型" style="width: 100%">
        <ElOption
          v-for="item in enumData.companyTypes"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </ElSelect>
    </ElFormItem>

    <!-- 上级物流公司 - 只在选择承运/快递公司时显示 -->
    <ElFormItem v-if="formData.company_type === 2" label="上级物流公司" prop="fl_id">
      <ElSelect v-model="formData.fl_id" placeholder="请选择上级物流公司" style="width: 100%">
        <ElOption
          v-for="item in enumData.parentCompanies"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </ElSelect>
    </ElFormItem>

    <!-- 公司名称 - 只在选择了公司类型后显示 -->
    <ElFormItem v-if="formData.company_type" label="公司名称" prop="name">
      <ElInput v-model="formData.name" placeholder="请输入公司名称" />
    </ElFormItem>

    <!-- 状态 - 只在选择了公司类型后显示 -->
    <ElFormItem v-if="formData.company_type" label="状态" prop="status">
      <ElSelect v-model="formData.status" placeholder="请选择状态" style="width: 100%">
        <ElOption
          v-for="item in enumData.statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </ElSelect>
    </ElFormItem>
  </ElForm>
</template>

<style scoped>
.el-select {
  width: 100%;
}
</style>
